import dictService from "@/api/services/system/dictService";
import menuService from "@/api/services/system/menuService";
import genService from "@/api/services/tool/genService";
import { Button, Checkbox, Col, Form, Input, Modal, Row, Select, Table, Tabs, TreeSelect, Typography } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import type { Dict, Menu } from "#/entity";
import type { GenTableColumn, TableInfo } from "./entity";

const { Title } = Typography;

// 生成模态框组件
interface GenModalProps {
	visible: boolean;
	editingRecord: TableInfo | null;
	onCancel: () => void;
	onSave: (formData: TableInfo, fieldData: GenTableColumn[]) => void;
}

const GenModal: React.FC<GenModalProps> = ({ visible, editingRecord, onCancel, onSave }) => {
	const [activeTab, setActiveTab] = useState("1");
	const [fieldData, setFieldData] = useState<GenTableColumn[]>([]);
	const [permissions, setPermissions] = useState<Menu[]>([]);
	const [dictOptions, setDictOptions] = useState<Dict[]>([]);
	const [tplCategory, setTplCategory] = useState<string>("");
	const [form] = Form.useForm();
	const [genTableList, setGenTableList] = useState<TableInfo[]>([]);
	//关联父表字段
	const [relateFiledList, setRelateFieldList] = useState<GenTableColumn[]>([]);

	// 字段表格列配置
	const getFieldColumns = (
		handleFieldChange: (columnId: string, field: string, value: any) => void,
	): ColumnsType<any> => [
		{
			title: "序号",
			dataIndex: "index",
			key: "index",
			width: 60,
			render: (_, __, index) => index + 1,
		},
		{
			title: "字段列名",
			dataIndex: "columnName",
			key: "columnName",
			width: 180,
		},
		{
			title: "字段描述",
			dataIndex: "columnComment",
			key: "columnComment",
			width: 150,
			render: (text, record) => (
				<Input value={text} onChange={(e) => handleFieldChange(record.columnId, "columnComment", e.target.value)} />
			),
		},
		{
			title: "物理类型",
			dataIndex: "columnType",
			key: "columnType",
			width: 120,
		},
		{
			title: "Java类型",
			dataIndex: "javaType",
			key: "javaType",
			width: 120,
			render: (text, record) => (
				<Select
					value={text}
					style={{ width: "100%" }}
					onChange={(value) => handleFieldChange(record.columnId, "javaType", value)}
					options={[
						{ value: "String", label: "String" },
						{ value: "Integer", label: "Integer" },
						{ value: "Long", label: "Long" },
						{ value: "Double", label: "Double" },
						{ value: "Boolean", label: "Boolean" },
						{ value: "LocalDateTime", label: "LocalDateTime" },
					]}
				/>
			),
		},
		{
			title: "Java属性",
			dataIndex: "javaField",
			key: "javaField",
			width: 120,
			render: (text, record) => (
				<Input value={text} onChange={(e) => handleFieldChange(record.columnId, "javaField", e.target.value)} />
			),
		},
		{
			title: "Typescript类型",
			dataIndex: "tsType",
			key: "tsType",
			width: 120,
			render: (text, record) => (
				<Select
					value={text}
					style={{ width: "100%" }}
					onChange={(value) => handleFieldChange(record.columnId, "tsType", value)}
					options={[
						{ value: "string", label: "string" },
						{ value: "number", label: "number" },
						{ value: "boolean", label: "boolean" },
						{ value: "Date", label: "Date" },
					]}
				/>
			),
		},
		{
			title: "插入",
			dataIndex: "isInsert",
			key: "isInsert",
			width: 80,
			align: "center",
			render: (text, record) => (
				<Checkbox
					checked={text === 1}
					onChange={(e) => handleFieldChange(record.columnId, "isInsert", e.target.checked)}
				/>
			),
		},
		{
			title: "编辑",
			dataIndex: "isEdit",
			key: "isEdit",
			width: 80,
			align: "center",
			render: (text, record) => (
				<Checkbox
					checked={text === 1}
					onChange={(e) => handleFieldChange(record.columnId, "isEdit", e.target.checked)}
				/>
			),
		},
		{
			title: "列表",
			dataIndex: "isList",
			key: "isList",
			width: 80,
			align: "center",
			render: (text, record) => (
				<Checkbox
					checked={text === 1}
					onChange={(e) => handleFieldChange(record.columnId, "isList", e.target.checked)}
				/>
			),
		},
		{
			title: "查询",
			dataIndex: "isQuery",
			key: "isQuery",
			width: 80,
			align: "center",
			render: (text, record) => (
				<Checkbox
					checked={text === 1}
					onChange={(e) => handleFieldChange(record.columnId, "isQuery", e.target.checked)}
				/>
			),
		},
		{
			title: "查询方式",
			dataIndex: "queryType",
			key: "queryType",
			width: 120,
			render: (text, record) => (
				<Select
					value={text}
					allowClear
					style={{ width: "100%" }}
					onChange={(value) => handleFieldChange(record.columnId, "queryType", value)}
					options={[
						{ value: "=", label: "=" },
						{ value: "!=", label: "!=" },
						{ value: ">", label: ">" },
						{ value: ">=", label: ">=" },
						{ value: "<", label: "<" },
						{ value: "<=", label: "<=" },
						{ value: "IN", label: "in" },
						{ value: "LIKE", label: "LIKE" },
						{ value: "BETWEEN", label: "BETWEEN" },
					]}
				/>
			),
		},
		{
			title: "必填",
			dataIndex: "isRequired",
			key: "isRequired",
			width: 80,
			align: "center",
			render: (text, record) => (
				<Checkbox
					checked={text === 1}
					onChange={(e) => handleFieldChange(record.columnId, "isRequired", e.target.checked)}
				/>
			),
		},
		{
			title: "显示类型",
			dataIndex: "htmlType",
			key: "htmlType",
			width: 120,
			render: (text, record) => (
				<Select
					value={text}
					allowClear
					style={{ width: "100%" }}
					onChange={(value) => handleFieldChange(record.columnId, "htmlType", value)}
					options={[
						{ value: "input", label: "文本框" },
						{ value: "textarea", label: "文本域" },
						{ value: "select", label: "下拉框" },
						{ value: "radio", label: "单选框" },
						{ value: "checkbox", label: "复选框" },
						{ value: "datetime", label: "日期控件" },
						{ value: "upload", label: "上传控件" },
						{ value: "editor", label: "富文本控件" },
					]}
				/>
			),
		},
		{
			title: "字典类型",
			dataIndex: "dictType",
			key: "dictType",
			width: 120,
			render: (text, record) => (
				<Select
					value={text}
					allowClear
					dropdownStyle={{ minWidth: 200 }}
					style={{ width: "100%" }}
					onChange={(value) => handleFieldChange(record.columnId, "dictType", value)}
					options={dictOptions.map((item) => ({
						value: item.dictCode,
						label: item.dictName,
					}))}
					optionRender={(option) => (
						<div>
							<span>{option.label}</span>
							<span style={{ color: "#999", marginLeft: 15 }}>{option.value}</span>
						</div>
					)}
				/>
			),
		},
	];

	// 处理字段变更
	const handleFieldChange = (id: string, field: string, value: any) => {
		// 如果是checkbox的值，将布尔值转换为数字值（true为1，false为0）
		const processedValue = typeof value === "boolean" ? (value ? 1 : 0) : value;
		setFieldData((prevData) =>
			prevData.map((item) => (item.columnId === id ? { ...item, [field]: processedValue } : item)),
		);
	};

	// 获取字段列配置
	const fieldColumns = getFieldColumns(handleFieldChange);

	// 获取菜单信息
	const getPermissions = async () => {
		menuService
			.queryAll()
			.then((res) => {
				setPermissions(res);
			})
			.catch((error) => {
				console.error("获取菜单列表失败:", error);
				toast.error("获取菜单列表失败:");
			});
	};

	//获取所有的生成表信息
	const getGenTableList = async () => {
		await genService
			.allList()
			.then((res) => {
				setGenTableList(res);
			})
			.catch((error) => {
				console.error("获取生成表信息失败", error);
				toast.error("获取生成表信息失败!");
			});
	};

	// 获取所有字典信息
	const getDictOptions = async () => {
		dictService
			.listAll()
			.then((res) => {
				setDictOptions(res);
			})
			.catch((error) => {
				console.error("获取字典失败:", error);
				toast.error("获取字典失败:");
			});
	};

	// 获取字段数据
	const fetchFieldData = () => {
		if (editingRecord?.tableId) {
			genService
				.columnList(editingRecord.tableId)
				.then((res) => {
					if (res) {
						setFieldData(res);
					}
				})
				.catch((error) => {
					console.error(error);
					toast.error("获取数据失败！");
				});
		}
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		getPermissions();
		getDictOptions();
		getGenTableList();
	}, [editingRecord]);

	// 当编辑记录变化时，更新表单值
	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		if (editingRecord) {
			form.setFieldsValue(editingRecord);
			setTplCategory((editingRecord as any).tplCategory || "");
			fetchFieldData();

			if ((editingRecord as any).tplCategory === "parent") {
				genService
					.getChildrenTable(editingRecord?.tableName)
					.then((res) => {
						if (res && res.length > 0) {
							const childrenTable = res.map((item) => `${item.tableName}[${item.tableComment}]`).join(",  ");
							form.setFieldValue("childrenTables", childrenTable);
						}
					})
					.catch((error) => {
						console.error(error.message);
						toast.error("获取子表信息失败!");
					});
			}
		}
	}, [editingRecord]);

	// 处理保存
	const handleSave = () => {
		form
			.validateFields()
			.then((values) => {
				// 获取表单数据和字段数据
				const formData = {
					...values,
					tableId: editingRecord?.tableId,
					tableName: values.tableName || editingRecord?.tableName,
					tableComment: values.tableComment || editingRecord?.tableComment,
					className: values.className || editingRecord?.className,
					packageName: values.packageName || editingRecord?.packageName,
					moduleName: values.moduleName || editingRecord?.moduleName,
					businessName: values.businessName || editingRecord?.businessName,
					functionName: values.functionName || editingRecord?.functionName,
					functionAuthor: values.author || editingRecord?.functionAuthor,
					parentMenuId: values.parentMenuId !== undefined ? values.menu : editingRecord?.parentMenuId,
					parentMenuName: values.parentMenuName || editingRecord?.parentMenuName,
					remark: values.remark || editingRecord?.remark,
				};

				// 调用父组件的onSave方法，传递表单数据和字段数据
				onSave(formData, fieldData);
			})
			.catch((error) => {
				console.error("表单验证失败:", error);
			});
	};

	//关联父表变换触发
	const handleParentTableChange = (value: string) => {
		// 先检查 genTableList 是否为空或未定义
		if (!genTableList || genTableList.length === 0) {
			console.warn("genTableList 为空或未定义");
			return null;
		}

		if (value) {
			// 查找匹配的表格
			const table = genTableList.find((item) => item.tableName === value);

			genService
				.columnList(table?.tableId || "")
				.then((res) => {
					setRelateFieldList(res);
				})
				.catch((error) => {
					console.error("获取父表字段失败", error);
					toast.error("获取父表字段失败!");
				});
		}
	};

	return (
		<Modal
			title={editingRecord ? "编辑表信息" : "新增表信息"}
			open={visible}
			onCancel={onCancel}
			width="100%"
			style={{ top: 0, maxWidth: "98vw", padding: 10 }}
			styles={{
				body: { height: "calc(100vh - 200px)", overflow: "auto", padding: "10px 24px" },
				content: { maxWidth: "100vw", overflow: "hidden" },
				header: { padding: "16px 24px" },
				footer: { padding: "10px 24px" },
			}}
			footer={[
				<Button key="cancel" onClick={onCancel}>
					取消
				</Button>,
				<Button key="submit" type="primary" onClick={handleSave}>
					保存
				</Button>,
			]}
		>
			<Tabs activeKey={activeTab} onChange={setActiveTab}>
				{/* 基础信息标签页 */}
				<Tabs.TabPane tab="基础信息" key="1">
					<Form
						form={form}
						layout="vertical"
						preserve={false}
						initialValues={{
							genType: "0",
							genPath: "/",
							tplCategory: "crud",
						}}
					>
						<Row gutter={24}>
							<Col span={12}>
								<Form.Item name="tableName" label="表名称" rules={[{ required: true, message: "请输入表名称" }]}>
									<Input placeholder="请输入表名称" />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item name="tableComment" label="表描述" rules={[{ required: true, message: "请输入表描述" }]}>
									<Input placeholder="请输入表描述" />
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={24}>
							<Col span={12}>
								<Form.Item
									name="className"
									label="实体类名称"
									rules={[{ required: true, message: "请输入实体类名称" }]}
								>
									<Input placeholder="请输入实体类名称" />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item name="functionAuthor" label="作者" rules={[{ required: true, message: "请输入作者" }]}>
									<Input placeholder="请输入作者" />
								</Form.Item>
							</Col>
						</Row>
						<Form.Item name="remark" label="备注">
							<Input.TextArea placeholder="请输入备注" rows={4} />
						</Form.Item>
					</Form>
				</Tabs.TabPane>

				{/* 字段信息标签页 */}
				<Tabs.TabPane tab="字段信息" key="2">
					<div>
						<Table
							rowKey="id"
							columns={fieldColumns}
							dataSource={fieldData}
							pagination={false}
							scroll={{ y: "calc(100vh - 340px)", x: "max-content" }}
						/>
					</div>
				</Tabs.TabPane>

				{/* 生成信息标签页 */}
				<Tabs.TabPane tab="生成信息" key="3">
					<Form form={form} layout="vertical">
						<Row gutter={24}>
							<Col span={12}>
								<Form.Item name="tplCategory" label="生成模板">
									<Select
										placeholder="请选择生成模板"
										options={[
											{ value: "crud", label: "单表（增删改查）" },
											{ value: "tree", label: "树表（增删改查）" },
											{ value: "parent", label: "父表（增删改查）" },
											{ value: "children", label: "子表（增删改查）" },
										]}
										onChange={(value) => setTplCategory(value)}
									/>
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item name="packageName" label="生成包路径" tooltip="生成在哪个java包下，例如 com.hgyc.mes.system">
									<Input placeholder="请输入生成包路径" allowClear />
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={24}>
							<Col span={12}>
								<Form.Item name="moduleName" label="生成模块名" tooltip="可理解为子系统名，例如 system">
									<Input placeholder="请输入生成模块名" allowClear />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item name="businessName" label="生成业务名" tooltip="可理解为功能英文名，例如 user">
									<Input placeholder="请输入生成业务名" allowClear />
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={24}>
							<Col span={12}>
								<Form.Item name="functionName" label="生成功能名" tooltip="用作类描述，例如 用户">
									<Input placeholder="请输入生成功能名" allowClear />
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item name="parentMenuId" label="上级菜单" tooltip="分配到指定菜单下，例如 系统管理">
									<TreeSelect
										fieldNames={{
											label: "name",
											value: "id",
											children: "children",
										}}
										allowClear
										treeData={permissions}
									/>
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={24}>
							<Col span={12}>
								<Form.Item name="genType" label="生成代码方式">
									<Select
										allowClear
										placeholder="请选择生成代码方式"
										options={[
											{ value: "0", label: "zip压缩包" },
											{ value: "1", label: "自定义路径" },
										]}
									/>
								</Form.Item>
							</Col>
						</Row>
						{tplCategory === "tree" && (
							<Row gutter={24}>
								<Col span={24}>
									<Title level={4} className="border-b border-border pb-2">
										其他信息
									</Title>
								</Col>
								<Col span={12}>
									<Form.Item
										name="treeCode"
										label="树编码字段"
										required={tplCategory === "tree"}
										tooltip="树显示的编码字段名， 如：dept_id"
									>
										<Select
											placeholder="请选择树编码字段"
											allowClear
											options={fieldData.map((item) => ({
												value: item.columnName,
												label: (
													<div style={{ display: "flex", justifyContent: "space-between" }}>
														<span>{item.columnName}</span>
														{/* 可以添加其他信息 */}
														{item.columnComment && <span style={{ color: "#999" }}>{item.columnComment}</span>}
													</div>
												),
											}))}
										/>
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item
										name="treeParentCode"
										label="父编码字段名"
										required={tplCategory === "tree"}
										tooltip="树显示的父编码字段名， 如：parent_Id"
									>
										<Select
											placeholder="请选择树父编码字段"
											allowClear
											options={fieldData.map((item) => ({
												value: item.columnName,
												label: (
													<div style={{ display: "flex", justifyContent: "space-between" }}>
														<span>{item.columnName}</span>
														{/* 可以添加其他信息 */}
														{item.columnComment && <span style={{ color: "#999" }}>{item.columnComment}</span>}
													</div>
												),
											}))}
										/>
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item
										name="treeName"
										label="树名称字段"
										required={tplCategory === "tree"}
										tooltip="树节点的显示名称字段名， 如：dept_name"
									>
										<Select
											placeholder="请选择树名称字段"
											allowClear
											options={fieldData.map((item) => ({
												value: item.columnName,
												label: (
													<div style={{ display: "flex", justifyContent: "space-between" }}>
														<span>{item.columnName}</span>
														{/* 可以添加其他信息 */}
														{item.columnComment && <span style={{ color: "#999" }}>{item.columnComment}</span>}
													</div>
												),
											}))}
										/>
									</Form.Item>
								</Col>
							</Row>
						)}
						{tplCategory === "parent" && (
							<Row gutter={24}>
								<Col span={24}>
									<Title level={4} className="border-b border-border pb-2">
										子表信息
									</Title>
								</Col>
								<Col span={24}>
									<Form.Item name="childrenTables" label="子表信息" noStyle>
										<input disabled style={{ width: "100%", height: "32px" }} />
									</Form.Item>
								</Col>
							</Row>
						)}
						{tplCategory === "children" && (
							<Row gutter={24}>
								<Col span={24}>
									<Title level={4} className="border-b border-border pb-2">
										关联信息
									</Title>
								</Col>
								<Col span={12}>
									<Form.Item
										name="parentTableName"
										label="关联父表的表名"
										required={tplCategory === "children"}
										tooltip="作为子表关联的父表表名"
									>
										<Select
											showSearch
											allowClear
											placeholder="请选择关联父表的表名"
											options={genTableList.map((item) => ({
												value: item.tableName,
												label: (
													<div style={{ display: "flex", justifyContent: "space-between" }}>
														<span>{item.tableName}</span>
														{/* 可以添加其他信息 */}
														{item.tableComment && <span style={{ color: "#999" }}>{item.tableComment}</span>}
													</div>
												),
											}))}
											onChange={handleParentTableChange}
										/>
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item
										name="parentTablePK"
										label="关联父表字段"
										required={tplCategory === "children"}
										tooltip="子表关联父表的字段名"
									>
										<Select
											placeholder="请选择关联父表字段"
											allowClear
											options={relateFiledList.map((item) => ({
												value: item.columnName,
												label: (
													<div style={{ display: "flex", justifyContent: "space-between" }}>
														<span>{item.columnName}</span>
														{/* 可以添加其他信息 */}
														{item.columnComment && <span style={{ color: "#999" }}>{item.columnComment}</span>}
													</div>
												),
											}))}
										/>
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item
										name="subTableFkName"
										label="关联外键名"
										required={tplCategory === "children"}
										tooltip="作为子表使用那个字段关联父表"
									>
										<Select
											placeholder="请选择关联外键名"
											allowClear
											options={fieldData.map((item) => ({
												value: item.columnName,
												label: (
													<div style={{ display: "flex", justifyContent: "space-between" }}>
														<span>{item.columnName}</span>
														{/* 可以添加其他信息 */}
														{item.columnComment && <span style={{ color: "#999" }}>{item.columnComment}</span>}
													</div>
												),
											}))}
										/>
									</Form.Item>
								</Col>
							</Row>
						)}
					</Form>
				</Tabs.TabPane>
			</Tabs>
		</Modal>
	);
};

export default GenModal;
